package work.jame.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import work.jame.blog.framework.exception.BusinessException;
import work.jame.blog.framework.utils.security.SpringSecurityUtils;
import work.jame.blog.pojo.UserRelation;
import work.jame.blog.mapper.UserRelationMapper;
import work.jame.blog.service.UserRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jame
 * @since 2023-05-14
 */
@Service
public class UserRelationServiceImpl extends ServiceImpl<UserRelationMapper, UserRelation> implements UserRelationService {

    @Override
    public Long queryFollowersCount(Long userId) {
        QueryWrapper<UserRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("followers_user_id", userId);
        return this.count(wrapper);
    }

    @Override
    public Long queryFollowingCount(Long userId) {
        QueryWrapper<UserRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.count(wrapper);
    }

    @Override
    public boolean queryUserFollowing(Long userId, Long followersUserId) {
        QueryWrapper<UserRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("followers_user_id", followersUserId);
        return this.count(wrapper) == 1;
    }

    @Override
    public boolean followUser(Long followUserId) {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        if (followUserId.equals(userId)) {
            throw new BusinessException("不能关注自己!");
        }
        if (this.queryUserFollowing(followUserId, userId)) {
            throw new BusinessException("你已经关注TA啦!");
        }
        UserRelation relation = new UserRelation();
        relation.setUserId(followUserId);
        relation.setFollowersUserId(userId);
        relation.setCare(false);
        return this.save(relation);
    }

    @Override
    public boolean cancelFollowUser(Long followUserId) {
        Long userId = SpringSecurityUtils.getCurrentLoginUserId();
        if (followUserId.equals(userId)) {
            throw new BusinessException("不能取关自己!");
        }
        if (!this.queryUserFollowing(followUserId, userId)) {
            throw new BusinessException("你还没有关注TA");
        }
        QueryWrapper<UserRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", followUserId)
                .eq("followers_user_id", userId);
        return this.remove(wrapper);
    }


}
